package com.travel.controller;

import com.travel.common.Result;
import com.travel.domain.entity.ScenicIntro;
import com.travel.service.ScenicIntroService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/scenicIntro")
public class ScenicIntroController {

    @Autowired
    private ScenicIntroService scenicIntroService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    private static final String CACHE_ALL_SCENIC_KEY = "scenic:intro:all"; // 所有景点列表缓存键
    private static final String CACHE_SCENIC_BY_ID_KEY = "scenic:intro:id:"; // 根据 ID 获取单个景点的缓存键

    @GetMapping("/all")
    public Result<List<ScenicIntro>> getAllScenic() {
        // 尝试从缓存中获取所有景点的数据
        List<ScenicIntro> cachedScenicList = (List<ScenicIntro>) redisTemplate.opsForValue().get(CACHE_ALL_SCENIC_KEY);
        if (cachedScenicList != null) {
            // 如果缓存中有数据，直接返回缓存数据
            return Result.success(cachedScenicList);
        }
        try {
            // 如果缓存中没有数据，从数据库查询
            List<ScenicIntro> scenicList = scenicIntroService.getAllScenic();

            // 将查询结果存入缓存（可以设置过期时间，如 1 小时，按需求设置）
            redisTemplate.opsForValue().set(CACHE_ALL_SCENIC_KEY, scenicList);

            return Result.success(scenicList);
        } catch (Exception e) {
            // 捕获异常并记录错误
            return Result.error("获取景点列表失败: " + e.getMessage());
        }
    }
    @GetMapping("/getOne/{id}")
    public Result<ScenicIntro> getScenicById(@PathVariable Long id) {
        // 尝试从缓存中获取单个景点的数据
        String scenicCacheKey = CACHE_SCENIC_BY_ID_KEY + id;
        ScenicIntro cachedScenic = (ScenicIntro) redisTemplate.opsForValue().get(scenicCacheKey);
        if (cachedScenic != null) {
            // 如果缓存中有数据，直接返回缓存数据
            return Result.success(cachedScenic);
        }
        try {
            // 如果缓存中没有数据，从数据库查询
            ScenicIntro scenic = scenicIntroService.getScenicById(id);

            if (scenic != null) {
                // 将查询结果存入缓存（可以设置过期时间，如 1 小时）
                redisTemplate.opsForValue().set(scenicCacheKey, scenic);
                return Result.success(scenic);
            } else {
                return Result.error("景点未找到");
            }
        } catch (Exception e) {
            // 捕获异常并记录错误
            return Result.error("获取景点信息失败: " + e.getMessage());
        }
    }
}
